package mo.byte_school;

import java.util.ArrayList;
import java.util.List;

public class L22 {

    private List<String> res = new ArrayList<>();

    public List<String> generateParenthesis(int n) {
        StringBuilder builder = new StringBuilder();
        backtrack(builder, 0, 0, n);
        return res;
    }

    private void backtrack(StringBuilder builder, int left, int right, int n) {
        if (right == n) {
            res.add(new String(builder));
            return;
        }
        if (left < n) {
            builder.append('(');
            backtrack(builder, left+1, right, n);
            builder.deleteCharAt(builder.length()-1);
        }
        if (right < left) {
            builder.append(')');
            backtrack(builder, left, right+1, n);
            builder.deleteCharAt(builder.length()-1);
        }

    }

    public static void main(String[] args) {
        L22 test = new L22();
        System.out.println(test.generateParenthesis(3));
    }

}
